FileManager.FileManager = function(config) {

    this.settings = config.settings;
    
    this.filesView = new FileManager.FilesGrid(this.settings.CurrentView);
    this.foldersTree = new FileManager.FoldersTree();
    this.tagsPanel = new FileManager.TagsPanel({ctParent:this});
    this.history = new FileManager.BrowserHistory();

    FileManager.FileManager.superclass.constructor.call(this, {
            id: config.id,
            manager: config.manager,
            title: Plugin.messages["FileManager.title"],
            width:850,
            height:560,
            minWidth: 730,
            minHeight: 400,
            x:10,
            y:10,
            iconCls: 'db-icn-computer',
            constrainHeader:true,  
            minimizable: true, 
            closable: true,
            maximizable: true,
            shadow: 'frame',
            shadowOffset: 3,
            
            tbar: new Ext.Toolbar({
                cls: 'db-menubar',
                items: [
		            {text: Plugin.messages["FileManager.menu.item.file"],menu: { items: [
		                {text: Plugin.messages["FileManager.menu.item.download"], iconCls:'db-icn-download', handler: function() { this.downloadSelected(); }, scope: this },
		                {text: Plugin.messages["FileManager.menu.item.upload"], iconCls:'db-icn-upload', handler: function() { this.upload(true); }, scope: this },
		                '-',
		                {text: Plugin.messages["FileManager.menu.item.email"], iconCls:'db-icn-email-attach', handler: function() { this.sendFiles(); }, scope: this  },
		                '-',
		                {text: Plugin.messages["FileManager.menu.item.new"], menu: { items: [
		                    {text: Plugin.messages["FileManager.menu.item.folder"], iconCls:'db-icn-folder-new', handler: function() { this.addFolder(); }, scope: this }
		                ]}},
		                '-',
		                {text: Plugin.messages["FileManager.menu.item.delete"], iconCls:'db-icn-delete', handler: function() { this.deleteSelected(false); }, scope: this },
		                {text: Plugin.messages["FileManager.menu.item.rename"], iconCls:'db-icn-rename', handler: function() { this.renameSelected(); }, scope: this },
		                {text: Plugin.messages["FileManager.menu.item.properties"], iconCls:'db-icn-properties', handler: function() { this.showSelectedItemsProperties(); }, scope: this }
		            ]}},
		            {text: Plugin.messages["FileManager.menu.item.edit"],menu : {items: [
			            {text: Plugin.messages["FileManager.menu.item.cut"], iconCls:'db-icn-cut', handler: function() { this.cutSelected(); }, scope: this },
			            {text: Plugin.messages["FileManager.menu.item.copy"], iconCls:'db-icn-copy', handler: function() { this.copySelected(); }, scope: this },
			            {text: Plugin.messages["FileManager.menu.item.paste"], iconCls:'db-icn-paste', handler: function() { this.pasteOnSelected(); }, scope: this },
			            '-',
			            {text: Plugin.messages["FileManager.menu.item.select_all"], handler: function() { this.selectAllItems(); }, scope: this }
			        ]}},
		            {text: Plugin.messages["FileManager.menu.item.view"],menu : {items: [
			            {text: Plugin.messages["FileManager.menu.item.back"], iconCls:'db-icn-back', handler: function() { this.goBack(); }, scope: this },
			            {text: Plugin.messages["FileManager.menu.item.forward"], iconCls:'db-icn-forward', handler: function() { this.goForward(); }, scope: this },
			            {text: Plugin.messages["FileManager.menu.item.up"], iconCls:'db-icn-up', handler: function() { this.goUp(); }, scope: this },
			            '-',
			            {text: Plugin.messages["FileManager.menu.item.refresh"], iconCls:'db-icn-refresh', handler: function() { this.refreshAll(); }, scope: this }	    
			        ]}}
            ]}),                
                         
            layout: 'border',
            items: [{
                region:'west',
                title: Plugin.messages["FileManager.layout.panel.folders"],
                collapsible: true,
                split:true,
                width: 210,
                minSize: 175,
                maxSize: 400,
                layout:'fit',
                items:
                    new Ext.TabPanel({
                        border:false,
                        activeTab:0,
                        tabPosition:'bottom',
                        autoScroll: true,
                        items: [this.foldersTree/*,this.tagsPanel*/]
                    })
            },{
                region:'center',
                id: 'db-fv-panel',
                activeItem: 0,
                layout:'card',                 
                items:[{
                    border: false,
                    layout:'border',
                    items:[{
                        region: 'center',
                        margins: '0 0 0 0',
                        autoScroll: true,
                        border:false,
                        layout: 'fit',
                        items: this.filesView
                    },{
                        region: 'south',
                        split:false,
                        height: 70,
                        autoScroll:false,
                        collapsible:false,
                        titlebar: false,
                        border:false,
                        cls: 'db-property-panel',
                        html: '<table width="100%"><tr><td colspan="2" id="pp-title" class="ppTitle"></td><td class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.created"]+':</td><td id="pp-created"><td class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.comment"]+':</td><td id="pp-comment"></td></tr>' +
                              '<tr><td width="10%" class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.size"]+':</td><td id="pp-size" width="25%"></td><td width="10%" class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.modified"]+':</td><td id="pp-modified" width="20%"></td><td width="10%" class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.status"]+':</td><td id="pp-status" width="30%"></td></tr>' +
                              '<tr><td class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.path"]+':</td><td colspan="5" id="pp-path"></td></tr></table>'
                        //html: '<table width="100%"><tr><td colspan="2" id="pp-title" class="ppTitle"></td><td class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.created"]+':</td><td id="pp-created"><td class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.comment"]+':</td><td id="pp-comment"></td></tr>' +
                        //      '<tr><td width="10%" class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.size"]+':</td><td id="pp-size" width="25%"></td><td width="10%" class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.modified"]+':</td><td id="pp-modified" width="20%"></td><td width="10%" class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.tags"]+':</td><td id="pp-tags" width="30%"></td></tr>' +
                        //      '<tr><td class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.path"]+':</td><td colspan="3" id="pp-path"></td><td class="ppLabel">'+Plugin.messages["FileManager.layout.panel.properties.status"]+':</td><td id="pp-status"></td></tr></table>'
                    }]                     
                    },{
                        bodyStyle: 'background-color:#000;',
                        border: false,
                        autoScroll:false                                
                }]
            }]    
    });
    this.on('render', this.filemanager_show, this);
    this.on('resize', this.filemanager_resize, this);
    
    // handeling files view event
    this.filesView.on("loadcomplete", this.filesView_load, this, true); 
    this.filesView.on("itemdblclick", this.filesView_dblclick, this, true);
    this.filesView.on('itemcontextmenu', this.filesView_contextmenu, this, true);
    this.filesView.on('containercontextmenu', this.filesView_containercontextmenu, this, true);
    this.filesView.on('selectionchange', this.filesView_select, this, true);
    this.filesView.on('itemdrop', this.filesView_itemdrop, this, true);
    
    // handling tree events
    this.foldersTree.on('folderclick', this.foldersTree_click, this);
    this.foldersTree.on('foldersload', this.foldersTree_load, this);
    this.foldersTree.on('contextmenu', this.foldersTree_contextmenu, this);
    this.foldersTree.on('foldermove', this.foldersTree_foldermove, this);
    this.foldersTree.on('folderdrop', this.foldersTree_folderdrop, this);
    this.foldersTree.on('collapsenode', this.foldersTree_collapse, this);  
    
    // handeling tag events
    this.tagsPanel.on('tagselect', this.tagsPanel_tagselect, this);
    this.tagsPanel.on('tagedit', this.tagsPanel_tagedit, this);
    this.tagsPanel.on('tagremove', this.tagsPanel_tagremove, this);     
};

Ext.extend(FileManager.FileManager, Ext.Window, {

    createWindow: function(config, cls) {
        var desktop = MyDesktop.getDesktop();
        var win = desktop.getWindow(config.id);
        if(!win){
            win = desktop.createWindow(config, cls)
        }    
        return win;
    },

    filemanager_show: function() {
        this.initToolbar(this.tbar);
        this.initAddressBar(this.tbar);
        this.initMenues();
        this.initKeyboard();
        this.filesView.loadView();
        
        // get window area elem for masking purpose
        this.cover = this.body.findParent('.x-window-bwrap');
    },
    
    filemanager_resize: function(win, width, height) {
        if(this.addressCombo)
            this.addressCombo.setWidth(width - 250);
    },
    
    filesView_load: function(grd) {
        
        this.currentFolderId = this.filesView.currentFolderId;
        this.currentFolderType = this.filesView.currentFolderType;
        this.currentPath = this.filesView.currentPath;
        
        // update UI
        this.setupHistory();
        this.setupToolBar();
        this.setupView();
        this.setupAddressBar();
        
        if (this.currentFolderType == FileManager.FolderType.TagsFolder || 
            this.currentFolderType == FileManager.FolderType.SearchResults ) {
            if(this.foldersTree.loaded)
                this.foldersTree.clearSelections();
            else
                this.foldersTree.loadTree();
            return;
        }
        
        if (this.foldersTree.getFolderById(this.currentFolderId))
            this.foldersTree.selectFolderById(this.currentFolderId); 
        else
            this.foldersTree.loadTree(); 
    },    
    
    foldersTree_load: function() {
        if (this.foldersTree.getFolderById(this.currentFolderId))
            this.foldersTree.selectFolderById(this.currentFolderId);
        else
            this.showFolder(this.foldersTree.getMyFoldersRoot().ID);
    },    
    
    foldersTree_click: function(nodeId) {
        this.loadFiles(nodeId);
    },    
    
    foldersTree_contextmenu: function(node, e) {
        var folder = this.foldersTree.getNodeFolder(node);
        this.contextFolders = new Array();
        this.contextFolders[0] = folder;
        
        var menu = null;
        switch(folder.Type)
        {
            case FileManager.FolderType.RootFolder:
                menu = this.rootMenu;
                break;
            
            case FileManager.FolderType.FileFolder:
                menu = this.folderMenu;
                break;
                            
            case FileManager.FolderType.SharedFolder:
                menu = this.sharedFolderMenu;
                break;
                
            case FileManager.FolderType.RecycleBin:
                menu = this.recyclebinMenu;
                break;                                                   
                
            default:
        }   
        
        if(menu)
            menu.show(node.ui.getAnchor())
    },
    
    foldersTree_foldermove: function(folder, targetFolder) {
        this.move([folder], null, targetFolder);
    },
    
    foldersTree_folderdrop: function(targetFolder, de) {
    
        if(de.data && de.data.selections && de.data.selections.length > 0) { // this means that drag source is a grid
            var record = de.data.selections[0];
            if(record.data.directory != null) { // this means drag source is ftp
                //this.ftpClient.downloadSelected(targetFolder.ID);
            } else if (record.data.name != null) { // this means drag source is file manager
                if (this.currentFolderId != targetFolder.ID)
                    this.move(this.filesView.getSelectedFolders(), this.filesView.getSelectedFiles(), targetFolder);
            }
        }   
    },
    
    loadFiles: function(folderId) {
        this.filesView.loadView(folderId);
    },
    
    showFolder: function(folderId) {
        this.filesView.loadView(folderId);
    },
    
    refreshView: function() {
        this.filesView.loadView(this.currentFolderId);
    },
    
    refreshTree: function() {
        this.foldersTree.loadTree();
    },
    
    refreshAddressBar: function() {
        RemoteMethods.GetCompletePathList(function(result) {
        	this.addressCombo.store.loadData(result);
        	this.allFolders = result;
        }, this);        
    },
    
    refreshAll: function() {
        this.refreshView();
        this.refreshTree();
        this.refreshAddressBar();
    },
    
    filesView_dblclick: function(grd, index, e) {
        
        switch (this.currentFolderType) {
            case FileManager.FolderType.RecycleBin:
                this.showSelectedItemsProperties();
                break;
            
            case FileManager.FolderType.PublishedFiles:
                this.publishFile(this.filesView.getSelectedFiles()[0]);
                break;
                
            case FileManager.FolderType.PublishedFolders:
                this.publishFolder(this.filesView.getSelectedFolders()[0]);
                break;                
                
            default:
                if(this.filesView.getSelectedFolders().length > 0)
                    this.showFolder(this.filesView.getSelectedFolders()[0].ID);
                else
                    this.openFile(this.filesView.getSelectedFiles()[0]);
                break;          
        }  
    },
    
    openFile: function(file) {
    
        var fileName = file.Name;
        
        var download = false;
        if (fileName.match(/\.jpg$|\.jpeg$|\.gif$|\.bmp$|\.png$/i)) {
            this.viewImage(file);
        } 
        else if (fileName.match(/\.mp3$|\.mov$|\.mp4$|\.m4v$|\.m4b$|\.3gp$|\.m4a$/i)) {
            //this.playMedia(file);
            download = true;
        }
        else if (fileName.match(/\.asf$|\.avi$|\.wmv$|\.mpg$|\.wma$/i) && (Ext.isIE === true)) {
            //this.playMedia(file);
            download = true;
        }
        else if  (fileName.match(/\.zip$/i)){
            //this.extract(file.ID);
            download = true;
        }     
        else if  (fileName.match(/\.pdf$|\.ps$/i)){
            //this.showPDF(file);
            download = true;
        }
                                       
        if(download) {    
            Ext.Msg.show({
                title:"Download '" + file.Name + "'?",
                msg: "Do you want to download '" + file.Name + "'?",
                buttons: Ext.Msg.YESNO,           
                icon: Ext.MessageBox.QUESTION,
                modal: false,
                scope: this,
                fn: function(btn) {
                    if(btn == 'yes') {
                        this.download(file.ID); 
                    }
                }
            });
        }
    },
    
    viewImage: function(file) {
        var win = this.createWindow({
            id: 'view-image-' + file.ID,
            iconCls: 'db-icn-image',
            constrainHeader: true,
            title: file.Name,
            width: 640,
            height: 480,
            layout: 'fit',
            bodyStyle: 'overflow:auto;background-color:#fff;padding:5px',
            html: '<img src="../file/public/download?FileID=' + file.ID + '&sessionId=' + MyDesktop.currentSessionId + '" alt="" />',
            
            buttons: [
                {text:'Close', handler: function(){ win.close(); }, scope:this}
            ]
            
        });
        
        win.show();
    },
    
    filesView_select: function(view, selections) {
        var folders = view.getSelectedFolders();
        var files = view.getSelectedFiles();
        var folderIds = new Array();
        var fileIds = new Array();
        var folderIndex = 0;
        var fileIndex = 0;
        var folder = null;
        var file = null;
        
        var totalSize = 0;
        var title = "";
        var created = null;
        var modified = null;
        var comment = "";
        var path = "";
        var status = "";
        var tags = "";
        
        if (folders == null)
            folders = new Array();
        
        if (files == null)
            files = new Array();
        
        while (folder = folders[folderIndex]) {
            folderIds[folderIndex] = folder.ID;
            folderIndex++;
        }
        
        while (file = files[fileIndex]) {
            fileIds[fileIndex] = file.ID;
            fileIndex++;
            totalSize += file.Size;
        }
        
        var CreateStatusString = function(s) {
            switch(s) {
                case FileManager.ObjectStatus.Shared:
                    return "Shared";
                    
                case FileManager.ObjectStatus.Published:
                    return "Published";
                    
                case FileManager.ObjectStatus.SharedPublished:
                    return "Shared & Published";  
                    
                default:
                    return "";                  
            }
        };
        
        if(folderIndex == 0 && fileIndex == 1) {
            file = files[0];
            title = file.Name;
            created = file.CreateDate;
            modified = file.LastModified;
            path = file.Path + "\\" + file.Name;
            totalSize = file.Size;
            comment = file.Description;
            tags = file.Tags;
            status = CreateStatusString(file.Status);
        }
        else if (folderIndex == 1 && fileIndex == 0) {
            folder = folders[0];
            title = folder.Name;
            created = folder.CreateDate;
            modified = folder.CreateDate;
            path = folder.Path + "\\" + folder.Name;
            comment = folder.Description;
            tags = folder.Tags;
            status = CreateStatusString(folder.Status);
        }
        else if (fileIndex + folderIndex > 1) {
            title = (fileIndex + folderIndex) + ' items selected';
        }
        
        Ext.get('pp-title').dom.innerHTML = title.ellipse(30);
        Ext.get('pp-created').dom.innerHTML = created ? Ext.util.Format.date(created, 'm/d/Y H:i') : '';
        Ext.get('pp-modified').dom.innerHTML = modified? Ext.util.Format.date(modified, 'm/d/Y H:i') : '';
        Ext.get('pp-path').dom.innerHTML = path.ellipse(60);
        Ext.get('pp-size').dom.innerHTML = Utility.formatSize(totalSize);
        Ext.get('pp-comment').dom.innerHTML = comment ? comment.ellipse(35) : "";        
        Ext.get('pp-status').dom.innerHTML = status;    
        //Ext.get('pp-tags').dom.innerHTML = tags;
    },    
    
    filesView_contextmenu: function(grd, e) {
        this.contextFolders = grd.getSelectedFolders();
        this.contextFiles = grd.getSelectedFiles();
        
        e.stopEvent();
        var coords = e.getXY();
        var selectionCount = this.contextFolders.length + this.contextFiles.length;
                
        // return if nothing is selected
        if (selectionCount == 0)
            return;
            
        if (selectionCount == 1) {
            
            // if the folder is selected
            if (this.contextFolders.length == 1) {
                switch (this.currentFolderType) {
                    case FileManager.FolderType.RecycleBin:
                        this.recyclebinItemsMenu.showAt([coords[0], coords[1]]);
                        break;
                        
                    case FileManager.FolderType.FileFolder:
                    case FileManager.FolderType.RootFolder:
                    case FileManager.FolderType.SearchResults:
                    case FileManager.FolderType.TagsFolder:
                        this.folderMenu.showAt([coords[0], coords[1]]);
                        break;
                        
                    case FileManager.FolderType.SharedDocuments:
                    case FileManager.FolderType.SharedFolder:   
                        this.sharedFolderMenu.showAt([coords[0], coords[1]]);
                        break;                                         
                        
                    case FileManager.FolderType.PublishedFolders:
                        this.publishedFoldersMenu.showAt([coords[0], coords[1]]);
                        break;
                }  
            } else {
                switch(this.currentFolderType) {
                    case FileManager.FolderType.RecycleBin:
                        this.recyclebinItemsMenu.showAt([coords[0], coords[1]]);
                        break;
                        
                    case FileManager.FolderType.FileFolder:
                    case FileManager.FolderType.RootFolder:
                    case FileManager.FolderType.SearchResults:
                    case FileManager.FolderType.TagsFolder:                    
                        this.setupFileMenu(this.fileMenu, this.contextFiles[0]);
                        this.fileMenu.showAt([coords[0], coords[1]]);
                        break;
                        
                    case FileManager.FolderType.SharedFolder:
                        this.setupFileMenu(this.sharedFileMenu, this.contextFiles[0]);
                        this.sharedFileMenu.showAt([coords[0], coords[1]]);
                        break;                                            
                        
                    case FileManager.FolderType.PublishedFiles:
                        this.publishedFilesMenu.showAt([coords[0], coords[1]]);
                        break;                        
                }                
            }            
        } else {
            switch (this.currentFolderType) {
                case FileManager.FolderType.RecycleBin:
                    this.recyclebinItemsMenu.showAt([coords[0], coords[1]]);
                    break;
                    
                case FileManager.FolderType.FileFolder:
                case FileManager.FolderType.RootFolder:
                case FileManager.FolderType.SearchResults:
                case FileManager.FolderType.TagsFolder:                
                    this.multipleItemsMenu.showAt([coords[0], coords[1]]);
                    break;
                    
                case FileManager.FolderType.SharedDocuments:
                case FileManager.FolderType.SharedFolder:
                    this.sharedItemsMenu.showAt([coords[0], coords[1]]);
                    break;                                  
            }
        }
    },
    
    filesView_containercontextmenu: function(view, e) {
        e.stopEvent();
        var coords = e.getXY();
        this.mainViewMenu.showAt([coords[0], coords[1]]);
    },
    
    filesView_itemdrop: function(de) {
    
        var targetFolderId = null;
        if(de.rowIndex === false) {
            targetFolderId = this.currentFolderId;
        } else {
            targetFolderId = this.filesView.store.getAt(de.rowIndex).data.id;
        }
        var targetFolder = this.foldersTree.getFolderById(targetFolderId);
        if(targetFolder == null)
            return;
    
        if(de.data && de.data.selections && de.data.selections.length > 0) { // this means that drag source is a grid
            var record = de.data.selections[0];
            if(record.data.directory != null) { // this means drag source is ftp
                //this.ftpClient.downloadSelected(targetFolderId);
            } else if (record.data.name != null) { // this means drag source is file manager
                if (this.currentFolderId != targetFolderId)
                    this.move(this.filesView.getSelectedFolders(), this.filesView.getSelectedFiles(), targetFolder);
            }
        } else if(de.data && de.data.node) {  // this means that drag source is a tree
            this.move([this.foldersTree.getNodeFolder(de.data.node)], null, targetFolder);
        } 
    },
    
    foldersTree_collapse: function(node) {
        RemoteMethods.TreeNodeCollapse(node.id);
    },
    
    tagsPanel_tagselect: function(tag) {
        var folderId = 'TagsFolder:' + tag
        this.showFolder(folderId);
    },
    
    tagsPanel_tagedit: function() {
        this.showFolder(this.currentFolderId);
    },
    
    tagsPanel_tagremove: function() {
        this.showFolder();
    },    
    
    search: function(keyword) {
        var folderId = 'SearchResults:' + keyword
        this.showFolder(folderId);    
    },
    
    changeView: function(view) {

        if(view)
            this.currentView = view;        
        else if (this.currentView == 'thumbs')
            this.currentView = 'tiles';
        else if (this.currentView == 'tiles')
            this.currentView = 'icons';            
        else if (this.currentView == 'icons')
            this.currentView = 'details';
        else if (this.currentView == 'details')
            this.currentView = 'thumbs';
        else
            this.currentView = this.settings.CurrentView;
            
        this.filesView.setupView(this.currentView);
        RemoteMethods.SaveFileManagerSetting('currentView', this.currentView);
        
        this.setupView(this.currentView);        
    },    
    
    setupHistory: function() {
        var tbBack = this.toolbar.items.get('tbBack');
        var tbForward = this.toolbar.items.get('tbForward');
        var tbUp = this.toolbar.items.get('tbUp');
        
        this.history.addEntry(this.currentFolderId);
        
        if (this.history.canGoBack())
            tbBack.enable();
        else
            tbBack.disable();
            
        if (this.history.canGoForward())
            tbForward.enable();
        else
            tbForward.disable();
            
        if (this.foldersTree.getParentFolder(this.currentFolderId))
            tbUp.enable();
        else
            tbUp.disable();
    },   
    
    goBack: function() {
        if (this.history.goBack())
            this.showFolder(this.history.getCurrentEntry());
    },

    goForward: function() {
        if (this.history.goForward())
            this.showFolder(this.history.getCurrentEntry());
    },

    goUp: function() {
        var parent = this.foldersTree.getParentFolder(this.currentFolderId);
        if (parent)
            this.showFolder(parent.ID);
    },     
    
    setupToolBar: function() {
        var tbDownload = this.toolbar.items.get('tbDownload');
        var tbMultipleUpload = this.toolbar.items.get('tbMultipleUpload');
        var tbEmail = this.toolbar.items.get('tbEmail');
        
        tbDownload.disable();
        tbMultipleUpload.disable();
        tbEmail.disable();
        
        switch (this.currentFolderType) {
            case FileManager.FolderType.RootFolder:
            case FileManager.FolderType.FileFolder:    
            case FileManager.FolderType.SharedFolder:    
                tbDownload.enable();
                tbMultipleUpload.enable();
                tbEmail.enable();            
                break;
                
            default:
                break;
        }
    },    
    
    setupView: function(view) {
        var pnl = this.getComponent('db-fv-panel');  
        pnl.layout.setActiveItem(0); 
            
        if (this.currentFolderType === FileManager.FolderType.SearchResults || 
            this.currentFolderType === FileManager.FolderType.TagsFolder) {
            this.filesView.getColumnModel().setHidden(1, false);
        } else {
            this.filesView.getColumnModel().setHidden(1, true);
        }
       
    },   
    
    setupAddressBar: function() {
        this.addressCombo.setValue(this.currentPath);
    },      
    
    createFolder: function(parentId) {
        Ext.MessageBox.prompt('New Folder', 'Please enter folder name:',
            function(btn, text) {
                if(btn != 'ok')
                    return;
                    
                var CreateFolderComplete = function(result,success,error) {
                    if(success) {
                        this.loadFiles(result.folderId);
                    } else {
                    	this.showError(error);                    	                        
                    }
                };
                    
                if (text != '') {
                    RemoteMethods.CreateFolder(parentId, text, CreateFolderComplete, this);
                }
            }, this); //end of show dialog
    },
    
    renameFolder: function(folder) {     
    
        Ext.Msg.show({
            title: 'Rename Folder',
            msg: 'Please enter folder name:',
            buttons: Ext.MessageBox.OKCANCEL,
            prompt: true,
            width: 250,
            value: folder.Name,
            scope: this,
            modal: false,
            fn: function(btn, text) {
                if(btn != 'ok')
                    return;
                
                if (text != '') {
                    RemoteMethods.RenameFolder(folder.ID, text,
                        function (result,success,error) {
                            if (success) {
                                this.refreshAll();
                            } else {
                                this.showError(error);
                            }
                        }, 
                    this); //end of service call
                }            
            }
        }); //end of show dialog
    },   
    
    renameFile: function(file) {
        Ext.Msg.show({
            title: 'Rename File',
            msg: 'Please enter file name:',
            buttons: Ext.MessageBox.OKCANCEL,
            prompt: true,
            width: 250,
            value: file.Name,
            modal: false,
            scope: this,
            fn: function(btn, text) {
                if(btn != 'ok')
                    return;
                
                if (text != '') {
                    RemoteMethods.RenameFile(file.ID, text,
                        function (result,success,error) {
                            if (success) {
                                this.refreshView();
                            } else {
                                this.showError(error);
                            }
                        }, 
                    this); //end of service call
                }            
            }
        }); //end of show dialog
    },
    
    commentFile: function(file) {
        Ext.Msg.show({
            title: 'Add Comment',
            msg: 'Please enter your comment:',
            buttons: Ext.MessageBox.OKCANCEL,
            prompt: true,
            width: 300,
            multiline: true,
            value: file.Description,
            modal: false,
            scope: this,
            fn: function(btn, text) {
                if(btn != 'ok')
                    return;
                
                if (text != '') {
                    RemoteMethods.CommentFile(file.ID, text,
                        function (result) {
                            if (result.CurrentStatus == FileManager.StatusCode.Success) {
                                this.refreshView();
                            } else {
                                this.showError(result.Description);
                            }
                        }, this); //end of service call
                }            
            }
        }); //end of show dialog
    },   
    
    deleteItems: function(folders, files)
    {
        var folderIds = new Array();
        var fileIds = new Array();
        var folderIndex = 0;
        var fileIndex = 0;
        var folder = null;
        var file = null;
        
        if (folders == null)
            folders = new Array();
        
        if (files == null)
            files = new Array();
        
        while (folder = folders[folderIndex]) {
            folderIds[folderIndex] = folder.ID;
            folderIndex++;
        }
        
        while (file = files[fileIndex]) {
            fileIds[fileIndex] = file.ID;
            fileIndex++;
        }
        
        var msg = "";
        var title = "";
        if (fileIndex + folderIndex > 1) {
            title = "Confirm Multiple Item Delete";
            msg = this.createConfirmBoxContent("Are you sure you want to delete these " + (fileIndex + folderIndex) + " items?", "delete_confirm.gif");
        } else {
            if (fileIndex == 1) {
                title = "Confirm File Delete";
                msg = this.createConfirmBoxContent("Are you sure you want to delete '" + files[0].Name + "'?", "delete_confirm.gif");
            } else {
                title = "Confirm Folder Delete";
                msg = this.createConfirmBoxContent("Are you sure you want to remove the folder '" + folders[0].Name + "' and all its contents?", "delete_confirm.gif");
            }
        }
        
        Ext.Msg.show({
            title: title,
            msg: msg,
            buttons: Ext.MessageBox.YESNO,
            width: 430,
            heigth: 80,
            modal: false,
            scope: this,
            fn: function(btn) {
                if(btn == 'yes'){
                    this.showProgressDialog("Deleting Items....");
                    RemoteMethods.Delete(folderIds, fileIds,
                        function (resultm,success,error) {
                            if (!success) {
                                this.showError(error);
                            }
                            this.hideProgressDialog();
                            this.refreshAll();
                        }, this); //end of service call            
                }
            }// end of messagebox function call
        }); 
    },    
    
    emptyRecycleBin: function() {
        var msg = this.createConfirmBoxContent("Are you sure you want to empty the Recycle Bin?", "delete_confirm.gif");
        
        Ext.Msg.show({
            title: 'Empty Recycle Bin',
            msg: msg,
            buttons: Ext.MessageBox.YESNO,
            width: 430,
            heigth: 80,
            modal: false,
            scope: this,
            fn: function(btn) {
                if(btn == 'yes') {
                    this.showProgressDialog("Emptying Recycle Bin...");
                    RemoteMethods.EmptyRecycleBin(                     
                        function(result) {
                            if (result.CurrentStatus == FileManager.StatusCode.Error) {
                                this.showError(result.Description);
                            }           
                            this.hideProgressDialog();
                            this.refreshView();
                        }, this); 
                }
            }
        });         
    },     
    
    move: function(folders, files, parentFolder)
    {
        if (parentFolder.Type != FileManager.FolderType.RootFolder && 
            parentFolder.Type != FileManager.FolderType.FileFolder &&            
            parentFolder.Type != FileManager.FolderType.RecycleBin && 
            parentFolder.Type != FileManager.FolderType.SharedFolder) {
            return;
        } 
            
        var folderIds = new Array();
        var fileIds = new Array();
        var folderIndex = 0;
        var fileIndex = 0;
        var folder = null;
        var file = null;
        var shared = true;
        
        if (folders == null)
            folders = new Array();
        
        if (files == null)
            files = new Array();
        
        while (folder = folders[folderIndex]) {
            folderIds[folderIndex] = folder.ID;
            folderIndex++;
                        
            // we don't want to allow the user to move shared items to the recycle bin
            if (parentFolder.Type == FileManager.FolderType.RecycleBin && (folder.Type == FileManager.FolderType.SharedFolder)) {
                this.deleteItems(folders, files);
                return;
            }
        }
        
        while (file = files[fileIndex]) {
            fileIds[fileIndex] = file.ID;
            fileIndex++;
            
            // we don't want to allow the user to move shared items to the recycle bin
            if (parentFolder.Type == FileManager.FolderType.RecycleBin && (file.Type == FileManager.FolderType.SharedFolder)) {
                this.deleteItems(folders, files);
                return;
            }            
        }
        
        if (fileIndex + folderIndex == 0)
            return;
        
        if (parentFolder.Type == FileManager.FolderType.RecycleBin) {
            var msg = "";
            var title = "";
            if (fileIndex + folderIndex > 1) {
                title = "Confirm Multiple Item Delete";
                msg = this.createConfirmBoxContent("Are you sure you want to send these " + (fileIndex + folderIndex) + " items to the Recycle Bin?", "delete_recyclebin.gif");
            } else {
                if (fileIndex == 1) {
                    title = "Confirm File Delete";
                    msg = this.createConfirmBoxContent("Are you sure you want to send '" + files[0].Name + "' to the Recycle Bin?", "delete_recyclebin.gif");
                } else {
                    title = "Confirm Folder Delete";
                    msg = this.createConfirmBoxContent("Are you sure you want to move the '" + folders[0].Name + "' folder and all its contents to the Recycle Bin?", "delete_recyclebin.gif");
                }
            }
            Ext.Msg.show({
                title: title,
                msg: msg,
                buttons: Ext.MessageBox.YESNO,
                width: 430,
                heigth: 80,
                modal: false,
                scope: this,
                fn: function(btn) {
                    if(btn == 'yes')
                        this.moveItems(folderIds, fileIds, parentFolder.ID);
                }
            });           
        } else {        
            this.moveItems(folderIds, fileIds, parentFolder.ID);
        }

    },
    
    moveToRecycleBin: function(folders, files) {
        var rb = this.foldersTree.getRecycleBin();
        if(rb)
            this.move(folders, files, rb);
        else
            this.deleteItems(folders, files);
    },

    moveItems: function(folderIds, fileIds, parentId)
    {
        RemoteMethods.Move(folderIds, fileIds, parentId,
            function (result,success,error) {
                if (!success) {
                    this.showError(error);
                }
                this.refreshAll();
            }, this); //end of service call
    },   
    
    copy: function(folders, files, targetFolder)
    {
        if (targetFolder.Type != FileManager.FolderType.RootFolder && 
            targetFolder.Type != FileManager.FolderType.FileFolder &&            
            targetFolder.Type != FileManager.FolderType.SharedFolder) {
            this.showError('Copying files and folders is not allowed here.');
            return;
        }    
    
        var folderIds = new Array();
        var fileIds = new Array();
        var folderIndex = 0;
        var fileIndex = 0;
        var folder = null;
        var file = null;
        
        if (folders == null)
            folders = new Array();
        
        if (files == null)
            files = new Array();
        
        while (folder = folders[folderIndex]) {
            folderIds[folderIndex] = folder.ID;
            folderIndex++;
        }
        
        while (file = files[fileIndex]) {
            fileIds[fileIndex] = file.ID;
            fileIndex++;
        }
        
        if (fileIndex + folderIndex == 0)
            return;
            
        this.showProgressDialog('Copying...');
        RemoteMethods.Copy(folderIds, fileIds, targetFolder.ID,
            function (result,success,error) {
                this.hideProgressDialog();
                if (!success) {
                    this.showError(error);
                }
                this.refreshAll();
            }, this); //end of service call 
    },
    
    cutSelected: function() {
        this.cutContext = {
            'folders' : this.filesView.getSelectedFolders(),
            'files' : this.filesView.getSelectedFiles()
        }
    },

    cutFolder: function(folder) {
        this.cutContext = {
            'folders' : [folder],
            'files' : []
        }
    },    
    
    copySelected: function() {
        this.copyContext = {
            'folders' : this.filesView.getSelectedFolders(),
            'files' : this.filesView.getSelectedFiles()
        }
    },

    copyFolder: function(folder) {
        this.copyContext = {
            'folders' : [folder],
            'files' : []
        }
    },    
    
    paste: function(folder) {
        if (this.copyContext) 
        {
            this.copy(this.copyContext.folders, this.copyContext.files, folder);
        } 
        else if (this.cutContext) 
        {
            this.move(this.cutContext.folders, this.cutContext.files, folder);
        }
        
        this.copyContext = null;
        this.cutContext = null;
    },

    pasteOnSelected: function() {
        var folder = this.foldersTree.getSelectedFolder();
        this.paste(folder);
    },    
    
    downloadSelected: function() {
        if(this.currentFolderType == FileManager.FolderType.RecycleBin)
            return;

        var files = this.filesView.getSelectedFiles();    
        if (files.length > 0)
            this.download(files[0].ID);
        else
            this.showError('Please select a file')
    },

    deleteSelected: function(sendToRecycleBin) {
        var files = this.filesView.getSelectedFiles();
        var folders = this.filesView.getSelectedFolders();
        
        //if(!sendToRecycleBin || this.currentFolderType == FileManager.FolderType.RecycleBin)
            this.deleteItems(folders, files);
        //else
        //    this.moveToRecycleBin(folders, files);
    },

    addFolder: function() {
        switch (this.currentFolderType) {
            case FileManager.FolderType.RootFolder:
            case FileManager.FolderType.FileFolder:
                this.createFolder(this.currentFolderId);
                break;      
                
            default:
                break;
        }
    },

    renameSelected: function() {
        var files = this.filesView.getSelectedFiles();
        var folders = this.filesView.getSelectedFolders();
        
        if (this.currentFolderType == FileManager.FolderType.RecycleBin)
            return;

        if(folders.length > 0) {
            switch (folders[0].Type) {
                case FileManager.FolderType.FileFolder:
                    this.renameFolder(folders[0]);
                    break;
       
                default:
                    break;
            }
            return;
        }
        
        if (files.length > 0)
            this.renameFile(files[0]);
    },

    selectAllItems : function() {
        this.filesView.selectAll();
    }, 
    
    showHelp: function() 
    {
        var dlg = this.createWindow({
            id: 'help-win',
            iconCls:'db-icn-help',
            title:'Help for FileManager',
            width:550,
            height:530,            
            shim:false,
            animCollapse:false,
            border:false,
            constrainHeader:true,
            bodyStyle: 'padding:5px;',
            layout: 'fit',
            html: '<iframe src="Help.aspx" style="width:100%;height:100%;background-color:transparent;" scrolling="auto" frameborder="0" allowtransparency="true" id="popupFrame" name="popupFrame" width="100%" height="100%"></iframe>',
                
            buttons: [
                {text:'Close',handler:function(){ dlg.close() }}
            ]
        });
        dlg.show();
    },
    
    showAddressBook: function() {
        var addressBook = new FileManager.AddressBook({
            title: 'Address Book'
        });
    },
    
    download: function(fileId) {
        if (this.currentFolderType == FileManager.FolderType.RecycleBin)
            this.showError('You cannot download a file from here.');
        else
            window.location = '../file/public/download?FileID=' + fileId + '&att=1&sessionId='+MyDesktop.currentSessionId;
    },
    
    upload: function() {

        if(this.uploadDialog) {
            this.uploadDialog.show();
            return;
        }    

        if (this.currentFolderType != FileManager.FolderType.RootFolder && 
            this.currentFolderType != FileManager.FolderType.FileFolder &&             
            this.currentFolderType != FileManager.FolderType.SharedFolder) {
            this.showError('You cannot upload files here.');
            return;
        }
        
        /*
        result = {
        	UploadKey:'uploadKey',
        	FolderID:this.currentFolderId,
        	MaxFileSize:  102400000, //100M
        	StorageLeft:  1024000000,//1G
        	BandwidthLeft:1024000000 //1G       	
        };
        
        if (this.settings.SingleUploadMode)
            this.singleUpload(result.FolderID,result.UploadKey);
        else
            this.multipleUpload(result);
        */
        
        RemoteMethods.GetUploadObject(this.currentFolderId, function(result,success,error) {
            if(success) {
                if (this.settings.SingleUploadMode)
                    this.singleUpload(result.FolderID, result.UploadKey);
                else
                    this.multipleUpload(result);
            } else {
                this.showError(error);
            }
        }, this);
    },
    
    multipleUpload: function(uploadInfo) {       
         
        var ft = '*.*';
        var fd = Plugin.messages["FileManager.upload.SWFUpload.filter"];        
        
        this.uploadDialog = this.createWindow({
            id: 'upload-dialog',
            iconCls:'db-icn-upload-local',
            maximizable: false,
            uploadUrl : '../file/upload',
            folderId : uploadInfo.FolderID,
            fileSize: uploadInfo.MaxFileSize,
            storageLeft: uploadInfo.StorageLeft,
            bandwidthLeft: uploadInfo.BandwidthLeft,
            fileTypes: ft,
            fileTypesDescription: fd,
            flashUrl: '../file/swfupload.swf',
            debugEnabled: false
        }, FileManager.upload.SWFUpload);
        
        this.uploadDialog.on('filecomplete', function(wnd, fileObj, folderId) {
            if (this.currentFolderId == folderId) {
                this.refreshView();
            }
        }, this);
        
        this.uploadDialog.on('queuecomplete', function(wnd, folderId) {
            if (this.currentFolderId != folderId) {
                Ext.Msg.show({
                    title: Plugin.messages["FileManager.upload.SWFUpload.title.complete"],
                    msg: Plugin.messages["FileManager.upload.SWFUpload.message.viewUploadedFile"],
                    buttons: Ext.Msg.YESNO,           
                    icon: Ext.MessageBox.QUESTION,
                    modal: false,
                    scope: this,
                    fn: function(btn) {
                        if(btn == 'yes') {
                            this.showFolder(folderId); 
                        }
                    }
                });                        
            }
        }, this);
        
        this.uploadDialog.on('switchclick', this.changeUploadControl, this);
        this.uploadDialog.on('close', function() {this.uploadDialog=null;}, this);   		                
         
        this.uploadDialog.show();              
    },

    singleUpload: function(folderId,postbackId) {
        
        this.uploadDialog = this.createWindow({        
            id: 'upload-dialog',
            title: Plugin.messages["FileManager.upload.SingleUpload.title"],
            iconCls: 'db-icn-upload',
            uploadUrl: "../file/upload",
            folderId: folderId,
            postbackId: postbackId
        }, FileManager.SingleUpload); 
        
        this.uploadDialog.on('switch', this.changeUploadControl, this);
        this.uploadDialog.on('complete', this.refreshView, this);
        this.uploadDialog.on('close', function() {this.uploadDialog=null;}, this);        
        
        this.uploadDialog.show();      
    },
    
    changeUploadControl: function() {
        if(this.uploadDialog) {
            this.uploadDialog.close();
            if(!this.uploadDialog) {
                this.settings.SingleUploadMode = !this.settings.SingleUploadMode;
                RemoteMethods.SaveFileManagerSetting('singleUploadMode', this.settings.SingleUploadMode);           
                this.upload();
            }
        }
    },

    showEditor: function(id, title, path, width, height) {
            
        var dlg = this.createWindow({
            id: 'zoho-editor-'+id,
            iconCls: 'db-icn-zoho',
            constrainHeader: true,
            width: width || 1000,
            height: height || 600,
            title: 'Zoho - ' + title,
            buttons: [
                {text:'Close',handler:function(){dlg.close();},scope:this}
            ]
        });
        
        var addFrame = function() {            
            dlg.body.createChild({
                tag: 'div',
                style: 'text-align:center;height:100%',
                html: '<iframe src="' + path + '" style="width:100%;height:100%;background-color:transparent;" scrolling="auto" frameborder="0" allowtransparency="true" id="popupFrame" name="popupFrame" width="100%" height="100%"></iframe>'
            });  
        };       
        addFrame.defer(1000, this);
        
        var forceClose = false;
        dlg.on('beforeclose', function(panel) {
            if (forceClose === true)
                return true;
            Ext.MessageBox.confirm("Confirm", 
            "Are you sure you want to close this window?",
            function (btn) {
                if (btn == 'yes') {        
                    forceClose = true;
                    dlg.close();
                }
            }, this);
            return false;
        }, this);            
        
        dlg.on('close', function() {
            this.refreshView();
        }, this);        
            
        dlg.show();  
    },
    
    playMedia: function(file) {

        var player = this.createWindow({
            id: 'media-player-' + file.ID,
            iconCls: 'db-icn-play',
            url: '../file/public/download?FileID=' + file.ID + '&att=1&FileName=' + file.Name + '&sessionId='+MyDesktop.currentSessionId,
            fileName: file.Name        
        }, FileManager.MediaPlayer);
        
        player.show();
    }, 
    
    showPDF: function(file) {
        
        var filePath = '../file/public/download?FileID=' + file.ID + '&sessionId=' + MyDesktop.currentSessionId;
        var embedStr = '<object classid="clsid:CA8A9780-280D-11CF-A24D-444553540000" width="100%" height="100%"><param name="src" value="' + filePath + '"><embed src="' + filePath + '"  width="100%" height="100%"><noembed> Your browser does not support embedded PDF files.</noembed></embed></object>'
    
        var dlg = this.createWindow({
            id: 'pdf-viewer-'+file.ID,
            iconCls: 'db-icn-adobe',
            constrainHeader: true,
            width: 800,
            height: 600,
            title: file.Name,
            html: embedStr
        });
            
        dlg.show();         
    },  
    
    tagItems: function(folders, files) {
        
        var folderIds = new Array();
        var fileIds = new Array();
        var folderIndex = 0;
        var fileIndex = 0;
        var folder = null;
        var file = null;
        
        if (folders == null)
            folders = new Array();
        
        if (files == null)
            files = new Array();
        
        while (folder = folders[folderIndex]) {
            folderIds[folderIndex] = folder.ID;
            folderIndex++;
        }
        
        while (file = files[fileIndex]) {
            fileIds[fileIndex] = file.ID;
            fileIndex++;
        }
        
        if (fileIndex + folderIndex == 0)
            return;
            
        this.tagsPanel.tagItems(folderIds, fileIds);
    },    
    
    sendFiles: function() {

        if(this.currentFolderType == FileManager.FolderType.RecycleBin)
            return;
        
        var files = this.filesView.getSelectedFiles();
        var folders = this.filesView.getSelectedFolders();
        if (files.length == 0 && folders.length > 0) {
            this.showError('Folders cannot be emailed. Please select a file or group of files to email.');
            return;
        }
        if(files.length == 0) {
            this.showError('Please select a file or group of files to email.');
            return;
        }
        
        // create an array of files
        var fileIds = new Array();
        var file = null;
        var fileIndex = 0;
        var totalSize = 0;
        while (file = files[fileIndex]) {
            fileIds[fileIndex] = file.ID;
            totalSize += file.Size;
            fileIndex++;
        }        
        
        var dlg = null;
            
        // Create the form
        var txtTo = new Ext.form.AddressBookField({
            fieldLabel: 'To',
            anchor: '80%',
            allowBlank:false,
            emptyText: 'Seperate Emails By ,'
        });
        
        var txtSubject = new Ext.form.TextField({
            fieldLabel: 'Subject',
            anchor: '80%'
        });
        
        var txtAttach = new Ext.form.TextField({
            fieldLabel: 'Attach'
        });
        
        var txtBody = new Ext.form.TextArea({
            fieldLabel: 'Body',
            name: 'body',
            anchor: '-2 -85'
        });
        
        var CallServer = function() {
            var to = txtTo.getValue();
            var subject = txtSubject.getValue();
            var body = txtBody.getValue();
            
            if(to.trim() == '')
                return;
            
            dlg.close();
            this.showProgressDialog("Sending Files...");
            
            RemoteMethods.EmailFiles(fileIds, to, subject, body,
                function (result,success,error) {  
                    this.hideProgressDialog();                      
                    if (!success) {                        
                        this.showError(error);
                    }
                }, this); //end of service call
        };        

        dlg = this.createWindow({     
            id: 'send-files',
            title: 'Email Selected Files',
            iconCls: 'db-icn-email-attach',
            width: 460,
            height: 330,
            bodyStyle: 'padding:5px 10px 0 10px',
            layout: 'fit',
            constrainHeader: true,
            
            items: new Ext.form.FormPanel({
                labelWidth: 50,
                labelAlign: 'right',
                border: false,
                bodyStyle: 'background-color:Transparent',
                
                items: [txtTo, txtSubject, txtAttach, txtBody]
            }),
            
            buttons: [
                {text:'Send',handler:CallServer,scope:this},
                {text:'Cancel',handler:function(){ dlg.close() }}
            ]
        });
        
        
            Ext.get(txtAttach.getEl().dom.parentNode).createChild({
                tag: 'span',
                style: 'display:block;padding-top:3px;',
                html: fileIndex + ' files selected, total size: ' + Utility.formatSize(totalSize)
            });
            txtAttach.getEl().remove();        
 
        
        dlg.show();

    },
    
    shareFolder: function(folder) {
        
       if ( folder.Type != FileManager.FolderType.FileFolder)
            return;          

        var sharingDialog = this.createWindow({
            id: 'share-folder',
            title: 'Share "' + folder.Name + '" Folder',
            iconCls: 'db-icn-group',
            folderId: folder.ID,
            maximizable: false,
            renderTo: Ext.get('x-desktop') // this needs to be changed to something flexible
        }, FileManager.SharingDialog);
        
        sharingDialog.on('save', function(fId, users) { 
            this.refreshAll();
            
            // there is nobody to notify
            if(users.length == 0)
                return;
            
            // send out emails
            this.showProgressDialog("Sending Notification Emails...");    
            RemoteMethods.SendSharingNotificationEmails(folder.ID, users, function(result) {
                this.hideProgressDialog();
                if (result.CurrentStatus != FileManager.StatusCode.Success) {                        
                    this.showError(result.Description);
                }
            }, this);
        }, this);
    },
    
    publishFile: function(file) {
    
        var pf = this.createWindow({
            id: 'publish-item',
            title: Plugin.messages["FileManager.PublishedFile.title"] + file.Name,
            iconCls: 'db-icn-world',
            resizable:false,
            constrainHeader:true,
            maximizable:false,    
            bodyStyle: "padding:5px",
            y: 30,
            fileId: file.ID
        }, FileManager.PublishedFile);
        
        pf.on('publish', this.refreshView, this);
        pf.on('unpublish', function(win) {
            this.unPublishFile(file);
        }, this);
        pf.on('email', function() {
            this.sendPublishedFileLink(file);
        }, this);
        pf.on('error', function(win, msg) {
            this.showError(msg);
        }, this);        
        
        pf.publish();   
    },    
    
    unPublishFile: function(file) {
        Ext.MessageBox.confirm(Plugin.messages["FileManager.PublishedFile.title.unpublish"] + file.Name, 
            Plugin.messages["FileManager.PublishedFile.unpublish.message"].replace("{1}",file.Name),
            function (btn) {
                if (btn == 'yes') {
                    RemoteMethods.UnPublishFile(file.ID, function(result,success,error) {
                        if (success)
                            this.refreshView();
                        else                     
                            this.showError(error);
                    }, this);                
                }
            }, this);
    },    
    
    publishFolder: function(folder) {
    
        var pf = this.createWindow({
            id: 'publish-item',
            title: Plugin.messages["FileManager.PublishedFolder.title"].replace("{1}",folder.Name),
            iconCls: 'db-icn-world',
            resizable:false,
            constrainHeader:true,
            maximizable:false,       
            bodyStyle: "padding:5px",
            y: 30,
            folderId: folder.ID
        }, FileManager.PublishedFolder);
        
        pf.on('publish', this.refreshView, this);
        pf.on('unpublish', function(win) {
            this.unPublishFolder(folder);
        }, this);
        pf.on('email', function() {
            this.sendPublishedFolderLink(folder);
        }, this);
        pf.on('error', function(win, msg) {
            this.showError(msg);
        }, this);        
        
        pf.publish();                                 
    },    
    
    unPublishFolder: function(folder) {
        Ext.MessageBox.confirm(Plugin.messages["FileManager.PublishedFolder.title.unpublish"]+" '" + folder.Name + "' ", 
            Plugin.messages["FileManager.PublishedFolder.unpublish.message"].replace("{1}",folder.Name),
            function (btn) {
                if (btn == 'yes') {
                    RemoteMethods.UnPublishFolder(folder.ID, function(result,success,error) {
                        if (success)
                            this.refreshView();
                        else                     
                            this.showError(error);
                    }, this);                
                }
            }, this);
    },
    
    sendPublishedFileLink: function(file) {
        var PublishFileResponse = function(result) {
            var pfi = result.ReturnValue;
            var subject = Plugin.messages["FileManager.PublishedFile.email.subject"] + this.settings.FirstName
            var body = Plugin.messages["FileManager.PublishedFile.email.body.hello"]+",\n" +
                       this.settings.FirstName + Plugin.messages["FileManager.PublishedFile.email.body.desc1"] +
                       Plugin.messages["FileManager.PublishedFile.directUrl"] + ":\n" + pfi.directUrl + 
                       Plugin.messages["FileManager.PublishedFile.email.body.desc2"] +
                       (pfi.EnableExpiration ? Plugin.messages["FileManager.PublishedFile.email.body.desc3"] + Date.parseDate(pfi.expireDate, 'Y/m/d H:i').format('m/d/Y \\a\\t h:i A') + '\n\n' : '') + 
                       Plugin.messages["FileManager.PublishedFile.email.body.desc4"];
            
            this.sendEmail(subject, body); 
        };
        RemoteMethods.PublishFile(file.ID, false, new Date(), false, PublishFileResponse, this);      
    },      
    
    sendPublishedFolderLink: function(folder) {
        var PublishFolderResponse = function(result) {
            var pfi = result.ReturnValue;                
            var subject = Plugin.messages["FileManager.PublishedFolder.email.subject"] + this.settings.FirstName
            var body = Plugin.messages["FileManager.PublishedFolder.email.body.hello"] + ",\n" +
                       this.settings.FirstName + Plugin.messages["FileManager.PublishedFolder.email.body.desc1"] +
                       "\n"+Plugin.messages["FileManager.PublishedFolder.directUrl"]+":\n" + pfi.directUrl + 
                       "\n"+Plugin.messages["FileManager.PublishedFolder.rssUrl"]+":\n" + pfi.rssUrl + 
                       Plugin.messages["FileManager.PublishedFolder.email.body.desc2"] +
                       (pfi.enableExpiration ? Plugin.messages["FileManager.PublishedFolder.email.body.desc3"] + Date.parseDate(pfi.expireDate, 'Y/m/d H:i').format('m/d/Y \\a\\t h:i A') + '\n' : '') + 
                       (pfi.enablePassword ?   Plugin.messages["FileManager.PublishedFolder.fieldset.protect.password"] + ': ' + pfi.password + '\n' : '') + 
                       (pfi.enableExpiration || pfi.enablePassword ? '\n' : '') +
                       Plugin.messages["FileManager.PublishedFolder.email.body.desc4"];
            
            this.sendEmail(subject, body); 
        };
        RemoteMethods.PublishFolder(folder.ID, false, new Date(), false, null, false, null, false, PublishFolderResponse, this);      
    },  
    
    sendEmail: function(subject, body) {
        
        var txtTo = new Ext.form.AddressBookField({
            fieldLabel: 'To',
            anchor: '80%',
            allowBlank:false,
            emptyText: 'Seperate Emails By ,'
        });
        
        var txtSubject = new Ext.form.TextField({
            fieldLabel: 'Subject',
            anchor: '80%',
            allowBlank:false,
            value: subject
        });
        
        var txtBody = new Ext.form.TextArea({
            fieldLabel: 'Body',
            anchor: '-2 -65',
            allowBlank:false,
            value: body
        });
        
        var dlg = null;

        var Send = function() {
            if(txtTo.isValid() && txtSubject.isValid() && txtBody.isValid()) {
                var to = txtTo.getValue();
                var subject = txtSubject.getValue();
                var body = txtBody.getValue();
                
                dlg.close();
                this.showProgressDialog("Sending Emails...");
                
                RemoteMethods.SendEmail(to, subject, body,
                    function (result) {  
                        this.hideProgressDialog();                      
                        if (result.CurrentStatus != FileManager.StatusCode.Success) {                        
                            this.showError(result.Description);
                        }
                    }, this); //end of service call
            }
        };               
        
        var dlg = this.createWindow({
            id: 'send-email',
            title: 'Send Email', 
            iconCls: 'db-icn-email',
            width: 665, 
            height: 330, 
            bodyStyle: 'padding:5px 10px 0 10px',
            layout: 'fit',
            constrainHeader: true,
            
            items: new Ext.form.FormPanel({
                labelWidth: 50,
                labelAlign: 'right',
                border: false,
                bodyStyle: "background-color:Transparent",
                
                items:[
                    txtTo, txtSubject, txtBody
                ]
            }),
            
            buttons: [
                {text:'Send', handler:Send, scope:this},
                {text:'Close',handler:function() {dlg.close()}}
            ]
        });
        
        dlg.show();        
    },    
    
    uploadFromUrl: function() {
    
        var ufu = this.createWindow({
            title: "Upload From Url",
            id: "upload-from-url",
            iconCls: 'db-icn-upload-url',
            resizable:false,
            constrainHeader:true,
            maximizable:false,   
            folderId: this.currentFolderId
        }, FileManager.UploadFromUrl);
        
        ufu.on('upload', function(wnd, folderId) {
            if (this.currentFolderId != folderId) {
                Ext.Msg.show({
                    title:"Upload Complete?",
                    msg: "Your file is uploaded. Do you want to view uploaded file?",
                    buttons: Ext.Msg.YESNO,           
                    icon: Ext.MessageBox.QUESTION,
                    modal: false,
                    scope: this,
                    fn: function(btn) {
                        if(btn == 'yes') {
                            this.showFolder(folderId); 
                        }
                    }
                });                        
            } else {
                this.refreshView();
            }
        }, this);        
        
        ufu.on('error', function(win, msg) {
            this.showError(msg);
        }, this);        
        
        ufu.show();   
    },      
    
    showProperties: function(query, title, width, heigth) {       
        // add a random param to the query
        query += "&sessionId="+MyDesktop.currentSessionId+"&rnd=" + Math.round(10000*Math.random()) 
        var propertiesFrame = '<div id="popupFrameBody" style="height:' + (heigth - 40) + 'px">'; 
        propertiesFrame += '<iframe src="../file/properties.jsp?' + query + '" style="width:100%;height:100%;background-color:transparent;" scrolling="auto" frameborder="0" allowtransparency="true" id="popupFrame" name="popupFrame" width="100%" height="100%"></iframe>';
        propertiesFrame += '</div>';
        
        var dialog = this.createWindow({
           title: title,
           iconCls: 'db-icn-info',
           id: 'property-window-' + query,
           html: propertiesFrame,
           buttons: [{text: 'Close',handler:function(){dialog.close()}}],
           width: width,
           heigth: heigth,
           maximizable: false,
           resizable: false,
           constrainHeader: true,
           bodyStyle:'padding:5px'
        }); 
        
        dialog.show();
        
        return false;     
    },

    showFolderProperties: function(folder) {
        switch (folder.Type)
        {
            case FileManager.FolderType.RootFolder:
                return this.showAccountProperties();
            
            case FileManager.FolderType.FileFolder:
                return this.showProperties("FolderID=" + folder.ID, folder.Name + " Properties", 320, 300);
                
            case FileManager.FolderType.RecycleBin:   
                return this.showProperties("FolderID=" + folder.ID, "Recycle Bin Properties", 320, 300);
                
            default:
                return;
                
        }
    },
    
    showAccountProperties: function() {
        this.showProperties("Account=1", "Account Properties", 610, 435);
    },

    showFileProperties: function(file) {
        return this.showProperties("FileID=" + file.ID, file.Name + " Properties", 320, 300);
    },

    showSelectedItemsProperties: function() {
        var files = this.filesView.getSelectedFiles();
        var folders = this.filesView.getSelectedFolders();
        
        if (files.length + folders.length == 0)
            return;
            
        if (files.length + folders.length == 1) {
            if (files.length == 1)
                this.showFileProperties(files[0]);
            else
                this.showFolderProperties(folders[0]);
            
            return;
        }
            
        var query = "";
        if (files.length > 0)
            query += "Files=";
        for (var i = 0; i < files.length; ++i) {
        	if(i>0) {
        		query += ",";
        	}
            query += files[i].ID;
        }
        if (query != "")
            query += "&";
        if (folders.length > 0)
            query += "Folders=";
        for (var i = 0; i < folders.length; ++i) {
        	if(i>0) {
        		query += ",";
        	}
            query += folders[i].ID;  
        }
        
        this.showProperties(query, "Multiple Items Properties", 320, 300);
    },  
    
    compress: function(folders, files)
    {
        var folderIds = new Array();
        var fileIds = new Array();
        var folderIndex = 0;
        var fileIndex = 0;
        var folder = null;
        var file = null;
        var archiveName = "";
        
        if (folders == null)
            folders = new Array();
        
        if (files == null)
            files = new Array();
        
        while (folder = folders[folderIndex]) {
            folderIds[folderIndex] = folder.ID;
            folderIndex++;
        }
        
        while (file = files[fileIndex]) {
            fileIds[fileIndex] = file.ID;
            fileIndex++;
        }
        
        // return if no file is selected
        if(folders.length + files.length == 0) {
            ShowErrorMessage('Please select a file.');
            return;
        }
        
        // select a name for the archive
        if (folders.length > 0)
            archiveName = folders[0].Name;
        else
            archiveName = files[0].Name;
        
        archiveName = (archiveName.indexOf(".") == -1) ? archiveName : archiveName.substr(0, archiveName.lastIndexOf("."));
        archiveName += ".zip";
        
        // dialog that contains copression form
        var dlg = null;
        var myTree = null;
        
        // Create the form
        var txtName = new Ext.form.TextField({
            fieldLabel: 'Archive Name',
            width:155,
            allowBlank:false,
            value: archiveName
        });
        
        var cmbMethod = new Ext.form.ComboBox({
            fieldLabel: 'Compression method',
            store: new Ext.data.SimpleStore({
                fields: ['level', 'levelname'],
                data : [['0','Store'],['1','Fastest'],['3','Fast'],['5','Normal'],['7','Good'],['9','Best']]
            }),
            displayField:'levelname',
            valueField: 'level',
            value: '5',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',            
            editable: false,
            width:155
        });
        
        var txtPass = new Ext.form.TextField({
            fieldLabel: 'Enter password',
            width:130,
            inputType: 'password'
        });
        
        var txtPass2 = new Ext.form.TextField({
            fieldLabel: 'Reenter password',
            width:130,
            inputType: 'password'
        });        
        
        CallServer = function() {
            var archiveName = txtName.getValue();
            var level = cmbMethod.getValue();
            var pass = txtPass.getValue();
            var repass = txtPass2.getValue();
            var selectedFolder = myTree.getSelectedFolder();
            
            if(archiveName.trim() == '') {
                ShowErrorMessage('Please enter archive name');
                return;
            }
            if(pass != repass) {
                ShowErrorMessage('Passwords don\'t match');
                return;
            }
            
            dlg.close();
            this.showProgressDialog("Creating the archive...");
            
            RemoteMethods.Compress(folderIds, fileIds, archiveName, level, pass, selectedFolder.ID,
                function (result) {
                    this.hideProgressDialog();
                    if (result.CurrentStatus == FileManager.StatusCode.Success) {
                        this.refreshView();
                    } else {
                        this.showError(result.Description);
                    }
                }, this); //end of service call
        };        
        
        // create the dialog
        var dlg = new Ext.Window({
            title: 'Archive name and parameters',
            iconCls: 'db-icn-compress',
            resizable:false,
            minimizable: false,
            maximizable: false,
            constrainHeader: true,
            modal: true,
            renderTo: this.cover,
            width: 420,
            height: 310,            
            bodyStyle: 'padding:5px 10px 0 10px',
            
            buttons: [
                {text:'OK', handler:CallServer, scope:this},
                {text:'Cancel', handler:function(){dlg.close()}}            
            ]
        });    
        
        var bodyEl = dlg.body.createChild({
            tag: 'div',
            html: '<div style="width:160px;float:left;"></div><div style="width:200px;float:right;"><span style="font-size:12px;padding-bottom:4px;display:block">Target folder:</span><div style="height:200px;overflow:auto;position:relative;background-color:#fff;border:solid 1px #7F9DB9;"></div></div><div class="x-clear"></div>'
        });
        
        var formHolderEl = Ext.get(bodyEl.dom.childNodes[0]);
        var treeHolderEl = Ext.get(bodyEl.dom.childNodes[1].childNodes[1]);
        
        myTree = new FileManager.FoldersTree();     
        myTree.render(treeHolderEl);
        myTree.on('load', function() { 
            var selectedFolder = myTree.getFolderById(this.currentFolderId);
            if(selectedFolder == null)
                myTree.selectRoot();
            else
                myTree.selectFolderById(this.currentFolderId);                
        }, this);
        myTree.loadTree(true);
       
        var compressForm = new Ext.form.FormPanel({
            labelAlign: 'top',
            border: false,
            bodyStyle: 'background-color:Transparent',
            items:[
                txtName,
                cmbMethod,
                new Ext.form.FieldSet({
                    title: 'Set password',
                    autoHeight:true,
                    items: [
                        txtPass,
                        txtPass2
                    ]
                })
            ]
        });        
        compressForm.render(formHolderEl); 
        
        dlg.show();
    },  
    
    extract: function(fileId)
    {
        // password dialog
        var password = "";
        var SetPassword = function() {   
            var txtPass =  new Ext.form.TextField({
                fieldLabel: 'Password',
                name: 'password',
                width:250,
                inputType: 'password'
            });
            var win = new Ext.Window({
                title: 'Enter Password',
                iconCls: 'db-icn-key',
                resizable:false,
                minimizable: false,
                maximizable: false,            
                constrainHeader: true,
                modal: true,
                renderTo: this.cover,
                width: 280,
                height: 125,                
                bodyStyle: 'padding:5px 10px 0 10px',
                
                items: new Ext.form.FormPanel({
                    labelAlign: 'top',
                    border: false,
                    bodyStyle: 'background-color:Transparent',
                    items: txtPass
                }),
                
                buttons: [
                    {text:'OK', handler:function(){ password = txtPass.getValue();win.close(); }, scope:this},
                    {text:'Cancel', handler:function(){ win.close() }}
                ]
            });
            win.show();
        }
            
        var dlg = null;
        var myTree = null;
        var CallServer = function() {
            var selectedFolder = myTree.getSelectedFolder();
            
            dlg.close();
            this.showProgressDialog("Extracting...");
            
            RemoteMethods.Extract(fileId, password, selectedFolder.ID,
                function (result) {
                    this.hideProgressDialog();
                    if (result.CurrentStatus == FileManager.StatusCode.Success) {
                        this.refreshAll();
                    } else {
                        this.showError(result.Description);
                    }
                }, this); //end of service call
        };        
        
        // create the dialog
        dlg = new Ext.Window({
            title: 'Extraction path and options',
            iconCls: 'db-icn-compress',
            resizable:false,
            minimizable: false,
            maximizable: false,            
            constrainHeader: true,
            modal: true,
            renderTo: this.cover,
            width: 280,
            height: 300,            
            bodyStyle: 'padding:5px 10px 0 10px',
            
            buttons: [
                {text:'OK', handler:CallServer, scope:this},
                {text:'Set Password', handler:SetPassword, scope:this},
                {text:'Cancel', handler:function(){ dlg.close() }}           
            ]
        });    
        
        var bodyEl = dlg.body.createChild({
            tag: 'div',
            html: '<span style="font-size:12px;padding-bottom:4px;display:block">Target folder:</span><div style="height:200px;overflow:auto;position:relative;background-color:#fff;border:solid 1px #7F9DB9;"></div>'
        });
        
        var treeHolderEl = Ext.get(bodyEl.dom.childNodes[1]);
        
        myTree = new FileManager.FoldersTree();        
        myTree.render(treeHolderEl);
        myTree.on('load', function() { 
            var selectedFolder = myTree.getFolderById(this.currentFolderId);
            if(selectedFolder == null)
                myTree.selectRoot();
            else
                myTree.selectFolderById(this.currentFolderId);                
        }, this);
        myTree.loadTree(true);
        
        dlg.show();
    },
    
    showProgressDialog: function(message) {
        this.progressDialog = new Ext.Window({
            resizable:false,
            closable: false,
            maximizable: false,
            minimizable: false,
            constrainHeader: true,
            modal: true,
            renderTo: this.cover,
            width: 245,
            height: 90,
            title: "Please Wait..."
            
        });    
        this.progressDialog.on('hide', function() {this.progressDialog.getEl().remove();}, this);
        
        // add dialog message
        this.progressDialog.body.createChild({
            tag: "div",
            cls: 'db-progress-bar',
            html: "<p>" + message + "</p><div><span>Loading...</span></div>"
        }); 
        
        // show the dialog
        this.progressDialog.show();
    },

    hideProgressDialog: function() {
        this.progressDialog.close();
    },
    
    showError: function(message) {
        Ext.MessageBox.alert("Error", message);
    },
    
    createConfirmBoxContent: function(message, imageName) {
        var text = '<div style="padding:5px">';
        text += '<img src="../file/images/manager/' + imageName + '" alt="" style="float:left;padding:5px 10px;" />';
        text += "<p>" + message + "</p>";
        text += '</div';
        return text;
    }       
    
});

// folder type enumeration
FileManager.FolderType = function() { throw "Invalid Operation"; }
FileManager.FolderType.None = 0;
FileManager.FolderType.RootFolder = 1;
FileManager.FolderType.RecycleBin = 2;
FileManager.FolderType.PhotoGallery = 3;
FileManager.FolderType.FileFolder = 4;
FileManager.FolderType.PhotoAlbum = 5;
FileManager.FolderType.MyNetwork = 6;
FileManager.FolderType.MyNetworkUser = 7;
FileManager.FolderType.SharedDocuments = 8;
FileManager.FolderType.SharedAlbums = 9;
FileManager.FolderType.SharedFolder = 10;
FileManager.FolderType.SharedAlbum = 11;
FileManager.FolderType.PublishedItems = 12;
FileManager.FolderType.PublishedFiles = 13;
FileManager.FolderType.PublishedFolders = 14;
FileManager.FolderType.SearchResults = 15;
FileManager.FolderType.TagsFolder = 16;

FileManager.StatusCode = function() { throw "Invalid Operation"; }
FileManager.StatusCode.Error = 0;
FileManager.StatusCode.Success = 1;

FileManager.FileManagerSetting = function() { throw "Invalid Operation"; }
FileManager.FileManagerSetting.CurrentView = 0;
FileManager.FileManagerSetting.CollapseFoldersPanel = 1;
FileManager.FileManagerSetting.CurrentHeight = 2;
FileManager.FileManagerSetting.SingleUploadMode = 3;

FileManager.ObjectStatus = function() { throw "Invalid Operation"; }
FileManager.ObjectStatus.None = 0;
FileManager.ObjectStatus.Shared = 1;
FileManager.ObjectStatus.Published = 2;
FileManager.ObjectStatus.SharedPublished = 3;